package org.android.bbdroid.storage;

import java.util.LinkedList;
import java.util.List;

import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;

public final class BBDroidPreferences
{

  private static BBDroidPreferences instance;
  private static final String[]PROJECTION = new String[]{
	  			BBDroidUris.ForumsColums._ID,
	  			BBDroidUris.ForumsColums.FORUM_NAME,
	  			BBDroidUris.ForumsColums.FORUM_URL };
  private static final String[]PROJECTION_NAME = new String[]{
	  			BBDroidUris.ForumsColums.FORUM_NAME };

  public static BBDroidPreferences getInstance()
  {
    if (instance == null)
      instance = new BBDroidPreferences();
    return instance;
  }

  public void addForumPreference(Context c, String name, String url)
  {
    ContentValues cv = new ContentValues();
    cv.put(BBDroidUris.ForumsColums.FORUM_NAME, name);
    cv.put(BBDroidUris.ForumsColums.FORUM_URL, url);
    c.getContentResolver().insert(BBDroidUris.ForumsColums.CONTENT_URI, cv);
  }

  public ForumPreference[] getForumPreferences(Context c)
  {
    Cursor cursor = getForumPreferencesCursor(c);
    List<ForumPreference> preferences = new LinkedList<ForumPreference>();
    while (cursor.moveToNext())
    {
      preferences.add(new ForumPreference(cursor.getInt(BBDroidUris.ForumsColums.FORUM_ID_INDEX), 
    		  							  cursor.getString(BBDroidUris.ForumsColums.FORUM_NAME_INDEX), 
    	  							  cursor.getString(BBDroidUris.ForumsColums.FORUM_URL_INDEX)));
    }
    return preferences.toArray(new ForumPreference[preferences.size()]);
  }

  public Cursor getForumPreferencesCursor(Context c)
  {
    return c.getContentResolver().query(BBDroidUris.ForumsColums.CONTENT_URI, PROJECTION, null, null, BBDroidUris.ForumsColums.DEFAULT_SORT_ORDER);
  }

  public String[] getForumPreferencesName(Context c)
  {
    Cursor cursor = c.getContentResolver().query(BBDroidUris.ForumsColums.CONTENT_URI, PROJECTION_NAME, null, null, BBDroidUris.ForumsColums.DEFAULT_SORT_ORDER);
    List<String> names = new LinkedList<String>();
    while (cursor.moveToNext())
      names.add(cursor.getString(0));
    
    return names.toArray(new String[names.size()]);

  }

  public void removeForumPreferences(Context c, int id)
  {
    Uri uri = ContentUris.withAppendedId(BBDroidUris.ForumsColums.CONTENT_URI, id);
    c.getContentResolver().delete(uri, null, null);
  }

  public static class ForumPreference
  {
    private int id;
    private String name;
    private String url;

    ForumPreference(int id, String name, String url)
    {
      this.name = name;
      this.url = url;
      this.id = id;
    }

    public int getId()
    {
      return this.id;
    }

    public String getName()
    {
      return this.name;
    }

    public String getUrl()
    {
      return this.url;
    }
  }
}